package br.com.gentech.commons.model.repository;

import org.apache.log4j.Logger;
import org.junit.internal.runners.InitializationError;
import org.junit.internal.runners.JUnit4ClassRunner;
import org.junit.runner.Description;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;

public class DefaultClassRunner extends JUnit4ClassRunner {
	
	private static final Logger log = Logger.getLogger(DefaultClassRunner.class);
	
	public DefaultClassRunner(Class<?> klass) throws InitializationError {
		super(klass);
	}

	protected static String displayName;

	protected static String getDisplayName() {
		return displayName;
	}

	protected static void setDisplayName(final String name) {
		displayName = name;
	}

	public static String getTestName() {
		if (displayName == null) {
			return null;
		}

		int last = displayName.indexOf('(');
		if (last < 0) {
			last = displayName.length() + 1;
		}
		return displayName.substring(0, last);
	}
	
	public static String getTestClassName() {
		if (displayName == null) {
			return null;
		}
		
		int first = displayName.indexOf('(');
		int last = displayName.indexOf(')');		
		return displayName.substring(first + 1, last);		
	}

	private static class NameListener extends RunListener { 
		/** Record start of tests, not suites */
		public void testStarted(Description description) throws Exception {
			log.debug(" STARTED: " + description.getDisplayName());
			setDisplayName(description.isTest() ? description.getDisplayName() : null);
		}

		public void testFinished(Description description) throws Exception {
			log.debug("FINISHED: " + description.getDisplayName());
			if (getDisplayName() != null)
				if (getDisplayName().equals(description.getDisplayName()))
					setDisplayName(null);
				else
					throw new Exception("Test name mismatch");
		}
	}

	@Override
	public void run(RunNotifier notifier) {
		notifier.addListener(new NameListener());
		super.run(notifier);
	}
	
}